package com.etalk.crm.controller;

import com.alibaba.fastjson.JSON;
import com.etalk.crm.pojo.ApiLog;
import com.etalk.crm.service.ApiLogService;
import com.etalk.crm.utils.RestResponseDTO;
import com.etalk.crm.utils.RestResponseStates;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

/**
 * 日志上报
 *
 * @author Terwer
 * @version 1.0
 * 2019/1/9 10:26
 **/
@RequestMapping("/apiLog")
@Controller
public class ApiLogController {
    private static final Logger logger = LogManager.getLogger(ApiLogController.class);

    @Resource
    private ApiLogService apiLogService;

    /**
     * 日志上报
     *
     * @param apiLog      日志
     * @param tokenString token
     * @param session     session
     * @return 结果
     */
    @ApiOperation(value = "日志上报", notes = "日志上报")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "apiLog", value = "日志信息", dataType = "ApiLog"),
            @ApiImplicitParam(name = "tokenString", value = "用户token", dataType = "String")
    })
    @RequestMapping(value = "/addApiLog", method = {RequestMethod.POST, RequestMethod.OPTIONS}, produces = "application/json;charset=utf-8")
    @ResponseBody
    public RestResponseDTO addApiLog(@RequestBody ApiLog apiLog, String tokenString, HttpSession session) {
        RestResponseDTO restResponseDTO = new RestResponseDTO();
        boolean flag = false;
        try {
            //提交试卷
            Integer personId = (Integer) session.getAttribute("person.id");
            apiLog.setPersonId(personId);
            logger.info("日志上报：入参=" + JSON.toJSONString(apiLog) + ",personid=" + personId);
            flag = apiLogService.addApiLog(apiLog);
        } catch (Exception e) {
            logger.error("日志上报失败：" + e.getMessage(), e);
            restResponseDTO.setStatus(RestResponseStates.SERVER_ERROR.getValue());
            restResponseDTO.setMsg(RestResponseStates.SERVER_ERROR.getMsg());
        }
        //操作失败
        if (!flag) {
            restResponseDTO.setStatus(RestResponseStates.SERVER_ERROR.getValue());
            restResponseDTO.setMsg(RestResponseStates.SERVER_ERROR.getMsg());
        } else {
            restResponseDTO.setStatus(RestResponseStates.SUCCESS.getValue());
            restResponseDTO.setMsg(RestResponseStates.SUCCESS.getMsg());
        }
        restResponseDTO.setData(null);
        return restResponseDTO;
    }
}
